#ifndef __MEVEN_H__
#define __MEVEN_H__

#include "vec.h"
#include "list.h"
#include "uthash.h"
#include "vec.h"
#include "cJSON.h"
#include <stdbool.h>
#define MEVEN_EVENT_CNT 7

typedef enum {
    FD_LISTEN,
    FD_CLIENT,
} FD_t;

typedef enum {
    EVENT_ACCEPT,
    EVENT_LISTEN,
    EVENT_CONNECT,
    EVENT_CLOSE,
    EVENT_DATA,
    EVENT_ERROR,
    EVENT_TIMEOUT,
} ENUM_EVENT;

typedef Vec(char) string;

/**
 * @brief 事件流，用于网络编程中实现
 * @param type: epoll文件描述符类型
 * @param udata: 用户数据
 * @param timeout: 超时时间
 * @param lastActivity: 上次活动时间
 * @param address: 连接地址
 * @param port: 连接端口
 */
typedef struct {
    int type;
    bool is_active;
    int fd;
    char *address;
    int port;
    unsigned long lastActivity;
    long timeout;
} even_detail;

typedef struct {
    struct epoll_event *event;
    struct list_head list;
} even_node;

typedef void (*evenCallback)(even_detail* event, char* data, int size);

typedef enum {
    MEVEN_HTTP_GET,
    MEVEN_HTTP_POST,
    MEVEN_HTTP_PUT,
    MEVEN_HTTP_DELETE,
    MEVEN_HTTP_HEAD,
    MEVEN_HTTP_OPTIONS,
    MEVEN_HTTP_PATCH,
    MEVEN_HTTP_TRACE,
    MEVEN_HTTP_CONNECT,
} HTTP_METHOD;

extern const char *methods[9];
// 定义http头部键值对哈希表结构
typedef struct {
    char *key;
    char *value;
    UT_hash_handle hh;
} http_table_t;

typedef struct {
    HTTP_METHOD method;
    string path;
    char version[16];
    http_table_t *headers;
} http_header_t;

typedef struct {
    string path;
    HTTP_METHOD method;
    http_header_t header;
    cJSON *body;
} http_request_t;

typedef enum {
    RESPONSE_OK = 200,
    RESPONSE_NOT_FOUND = 404,
    RESPONSE_BAD_REQUEST = 401,
}RESPONSE_CODE;

extern string default_err_json;

typedef void (*httpCallback)(even_detail* event, http_request_t* header);

// 定义哈希表条目结构
typedef struct {
    char *key;         // 键，modth+路径
    httpCallback callback;   // 值，回调函数
    UT_hash_handle hh;     // 使结构体可哈希化
} method_table_t;

typedef struct {
    char* router;
    httpCallback callback;
} router_t;

typedef struct {
    int epoll_fd;
    int even_cnt;
    even_node even_list;
    method_table_t *method_table;
    Vec(router_t) routers;
    evenCallback listeners[MEVEN_EVENT_CNT];
} meven_t;

meven_t *meven_init();

void meven_setCallback(meven_t *meven, ENUM_EVENT type, evenCallback cb);

void meven_listen(meven_t *meven, int port);

void meven_loop(meven_t *meven);

void meven_add_router(meven_t *meven, const char *router, httpCallback callback);

void meven_setMethod(meven_t *meven, HTTP_METHOD method, const char* path, httpCallback callback);

char *http_get_header(http_header_t *header, const char *key);

cJSON *http_create_response(RESPONSE_CODE code, char* message, cJSON *data);

void sendBadRequest(even_detail *event, http_request_t *request);

#endif